/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package babydisco.Math;

import java.util.ArrayList;

/**
 *
 * @author Florian
 */
public class Spectogram {

    private ArrayList<Double> input;
    private ArrayList<Fourier> slices; //the main arraylist is the time axis, the individual fourier slices are the y-axis
    private double sampleFreq;
    private int sliceSize = 1024/4, overlap = 100;
    //length of a slice should be somewhere from .5 ECG  to about 1.8 ECG
       //average interval between 2 R peaks: 0.6 till 1.2s
       // slices need to cover .5 to 1.8 ECG so, 0.3 to 2,16s
       //slices need to be of length 2^X for fft to work
       // 1 timestep = 1ms
       // let's take 1024 timesteps since this would fit nicely

    //overlap is needed to not get artifacts at the sides edges of the slices.
    //100 seems like a nice number.

    //the fourier transformed slices now cover 1024ms, of which the first 100ms 
    //is the same as the last 100 ms of the previous slice

    public Spectogram(ArrayList<Double> input, double sampleFreq){
        this.input = input;
        this.sampleFreq = sampleFreq;
        transForm(createSlices());
    }

    public ArrayList<Fourier> getSlices(){
        return slices;
    }

    public double getSliceSize(){
        return sliceSize;
    }
    private ArrayList<ArrayList<Double>> createSlices(){
       double alpha = 0.16; // alpha for the unqualified Blackman window
       double alpha0 = (1-alpha)/2;
       double alpha1 = 1/2;
       double alpha2 = alpha/2;

       ArrayList<ArrayList<Double>> temp = new ArrayList<ArrayList<Double>>();
       for(int i = 0; i < (input.size()+overlap)/ sliceSize; i++){
           ArrayList<Double> temp2 = new ArrayList<Double>();

           if(i!=0){
            for(int j =-overlap; j < sliceSize-overlap; j ++){
                double weigth = alpha0- alpha1 *Math.cos((2*Math.PI*j) / (sliceSize-1)) + alpha2 * Math.cos((4*Math.PI*j) / (sliceSize-1));
                temp2.add( weigth * input.get(j + i*sliceSize));
                }
                temp.add(temp2);
           }
            else{
                for(int j =0; j < sliceSize; j ++){
                double weigth = alpha0- alpha1 *Math.cos((2*Math.PI*j) / (sliceSize-1)) + alpha2 * Math.cos((4*Math.PI*j) / (sliceSize-1));
                temp2.add(weigth * input.get(j + i*sliceSize));
                }
                temp.add(temp2);
            }
       }
       System.out.println(temp.size());
       return temp;


    }
    //transform the slices into fouriers
    private void transForm(ArrayList<ArrayList<Double>> list){
            slices = new ArrayList<Fourier>();
            for(int i = 0 ; i < list.size(); i ++){
                slices.add(new Fourier(list.get(i), sampleFreq));
            }
    }
}
